package edu.upc.autopartescybershop.web;

import edu.upc.autopartescybershop.domain.Modelo;
import edu.upc.autopartescybershop.service.ModeloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Carlos
 */
@Controller
public class ModelosController
{

    @Autowired
    ModeloService modeloService;

    @RequestMapping(value = "/modelos.htm", method = RequestMethod.GET)
    public ModelAndView listadoModelos()
    {
        ModelAndView mav = new ModelAndView("modelos");
        mav.addObject("listadoModelos", modeloService.obtenerModelos());
        return mav;
    }

    @RequestMapping(value = "/modelos_form.htm", method = RequestMethod.GET)
    public
    @ModelAttribute("modelo")
    Modelo setupForm(@RequestParam("accion") String accion, @RequestParam("id") int codigoModelo)
    {
        if (accion.equals("E"))
        {
            return modeloService.obtenerModelo(codigoModelo);
        }
        else if (accion.equals("D"))
        {
            Modelo modelo = modeloService.obtenerModelo(codigoModelo);
            modelo.setNombre("-*D*-");
            return modelo;
        }
        else if (accion.equals("N"))
        {
            return new Modelo();
        }
        else
        {
            return null;
        }
    }

    @RequestMapping(value = "/modelos_form.htm", method = RequestMethod.POST)
    public String onsubmit(@ModelAttribute("modelo") Modelo modelo,
            BindingResult result, SessionStatus status, @RequestParam("accion") String accion, @RequestParam("id") int codigoModelo)
    {
        if (accion.equals("E") || accion.equals("N"))
        {
            modeloService.grabarModelo(modelo);
        }
        else if (accion.equals("D"))
        {
            modeloService.eliminarModelo(codigoModelo);
        }
        return "redirect:/modelos.htm";
    }
}
